﻿package spring_user;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;










import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPListParseEngine;
import org.apache.commons.net.ftp.FTPReply;

import sun.net.TelnetInputStream;
import zttc.itat.model.FileInfo;
import zttc.itat.model.SystemContext;
import zttc.itat.model.User;



public class UploadFile {
	
	private static String encoding = System.getProperty("file.encoding");
	private String ftp_server;
	private String ftp_user;
	private String ftp_password;
	private String testUpload;
	private PropertyReader pr;
	private FTPClient ftpClient;
	public UploadFile()
	{
	 pr = new PropertyReader("wltx.properties");
	 ftp_server = pr.getProperty("ftp_server");
	 ftp_user =pr.getProperty("ftp_user");
	 ftp_password =pr.getProperty("ftp_password");
	 testUpload = pr.getProperty("projectDir");
	 ftpClient = new FTPClient();
	
	}
	private static UploadFile _instance = new UploadFile();

	public UploadFile getInstance() {
		if (_instance == null)
			_instance = new UploadFile();
		return _instance;
	}

	
	public boolean UploadFile(InputStream input, String fileName,myProgressListener listener,User loginUser) throws Exception {
		Date dd=new Date();	
		String remote=testUpload+"/"+loginUser.getId()+"/"+DateUtil.getYear(dd)+"/"+DateUtil.getMonth(dd)+"/"+DateUtil.getDay(dd)+"/"+fileName;
		return UploadFile(ftp_server, ftp_user, ftp_password, 21, input, remote,listener);
	}

	/**
	 * UploadFtp( FTP服务器IP, FTP用户名, FTP密码, 要上传的本地文件, 上传到FTP上的文件路径和文件名 )
	 * 
	 * @param server
	 * @param username
	 * @param password
	 * @param local
	 * @param remote
	 * @return
	 */
	public boolean UploadFile(String server, String username, String password,
			int port, InputStream input, String remote,myProgressListener listener) throws Exception {
		OutputStream outputStream=null; 
		int reply;
		try {
			ftpClient.connect(server, port);
			
			reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				return false;
			}
		} catch (IOException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return false;
				}
			}
			e.printStackTrace();
		}

		try {
			if (!ftpClient.login(username, password)) {
				ftpClient.logout();
				return false;
			}
			ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
			ftpClient.setControlEncoding("utf-8");
			ftpClient.enterLocalPassiveMode();
			
			String[] dirArray = remote.split("/");
			if (dirArray.length > 1) {
				for (int i = 0; i < dirArray.length - 1; i++) {

					if (dirArray[i] != null && dirArray[i] != null)
						if (!ftpClient.changeWorkingDirectory(dirArray[i])) {
							ftpClient.makeDirectory(dirArray[i]);
							ftpClient.changeWorkingDirectory(dirArray[i]);
						}
				}
			}
			int n = -1;
			long pContentLength = input.available();
			long trans = 0;
			int bufferSize = ftpClient.getBufferSize();
			byte[] buffer = new byte[bufferSize];
			System.out.println(new String(dirArray[dirArray.length - 1].getBytes(encoding)));
			outputStream = ftpClient.storeFileStream(new String(dirArray[dirArray.length - 1].getBytes(encoding),"iso-8859-1"));
			while ((n = input.read(buffer)) != -1) {
				outputStream.write(buffer,0,n);
				trans += n;
				listener.update(trans, pContentLength, 1,remote);
				
			}
			
		} catch (FTPConnectionClosedException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return false;
				}
			}
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return false;
				}
			}
			e.printStackTrace();
			return false;
		} finally {
			input.close();
			outputStream.flush();
			outputStream.close();
			ftpClient.logout();
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return false;
				}
			}
			
		}
		return true;
	}
	
	/**
     * Description: 从FTP服务器下载文件
     *
     * @Version1.0
     * @param url
     *            FTP服务器hostname
     * @param port
     *            FTP服务器端口
     * @param username
     *            FTP登录账号
     * @param password
     *            FTP登录密码
     * @param remotePath
     *            FTP服务器上的相对路径
     * @param fileName
     *            要下载的文件名
     * @param localPath
     *            下载后保存到本地的路径
     * @return
     */
    public  boolean downFile(String path) {
    	System.out.println(path);
        boolean result = false;
        int index = path.lastIndexOf("/");  
        //将字符串转为字符数组  
        char[] ch = path.toCharArray();  
        //根据 copyValueOf(char[] data, int offset, int count) 取得最后一个字符串  
        String fileName = String.copyValueOf(ch, index + 1, ch.length - index - 1);  
        String remotePath= "/"+String.copyValueOf(ch, 0 , index);
        try {
            int reply;
            ftpClient.setControlEncoding(encoding);
             
            /*
             *  为了上传和下载中文文件，有些地方建议使用以下两句代替
             *  new String(remotePath.getBytes(encoding),"iso-8859-1")转码。
             *  经过测试，通不过。
             */
//            FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
//            conf.setServerLanguageCode("zh");
 
            ftpClient.connect(ftp_server, 21);
            // 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftpClient.login(ftp_user, ftp_password);// 登录
            // 设置文件传输类型为二进制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 获取ftp登录应答代码
            reply = ftpClient.getReplyCode();
            // 验证是否登陆成功
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                System.err.println("FTP server refused connection.");
                return result;
            }
            // 转移到FTP服务器目录至指定的目录下
            ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1"));
            
            // 获取文件列表
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File("D:" + "/" + ff.getName());
                    OutputStream is = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }
 
            ftpClient.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }
 
    
    /**
     * Description: 从FTP服务器下载文件
     *
     * @Version1.0
     * @param url
     *            FTP服务器hostname
     * @param port
     *            FTP服务器端口
     * @param username
     *            FTP登录账号
     * @param password
     *            FTP登录密码
     * @param remotePath
     *            FTP服务器上的相对路径
     * @param fileName
     *            要下载的文件名
     * @param localPath
     *            下载后保存到本地的路径
     * @return
     */
   /* public  boolean downFile(String path) {
    	System.out.println(path);
        boolean result = false;
        int index = path.lastIndexOf("/");  
        //将字符串转为字符数组  
        char[] ch = path.toCharArray();  
        //根据 copyValueOf(char[] data, int offset, int count) 取得最后一个字符串  
        String fileName = String.copyValueOf(ch, index + 1, ch.length - index - 1);  
        String remotePath= "/"+String.copyValueOf(ch, 0 , index);
        try {
            int reply;
            ftpClient.setControlEncoding(encoding);
             
            
             *  为了上传和下载中文文件，有些地方建议使用以下两句代替
             *  new String(remotePath.getBytes(encoding),"iso-8859-1")转码。
             *  经过测试，通不过。
             
//            FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
//            conf.setServerLanguageCode("zh");
 
            ftpClient.connect(ftp_server, 21);
            // 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftpClient.login(ftp_user, ftp_password);// 登录
            // 设置文件传输类型为二进制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 获取ftp登录应答代码
            reply = ftpClient.getReplyCode();
            // 验证是否登陆成功
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                System.err.println("FTP server refused connection.");
                return result;
            }
            // 转移到FTP服务器目录至指定的目录下
            ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1"));
            ftpClient.registerSpyStream(spystream);
            // 获取文件列表
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File("D:" + "/" + ff.getName());
                    OutputStream is = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }
 
            ftpClient.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }*/
 

	/**
	 * 删除文件
	 * 
	 * @param server
	 * @param username
	 * @param password
	 * @param remote
	 * @return
	 */
	public boolean DeleteFile(String server, String username, String password,
			String remote) throws Exception {
		 
		int reply;
		try {
			ftpClient.connect(server);
			reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				return false;
			}
		} catch (IOException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return false;
				}
			}
			e.printStackTrace();
		}

		try {
			if (!ftpClient.login(username, password)) {
				ftpClient.logout();
				return false;
			}
			ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			String[] dirArray = remote.split("/");
			if (dirArray.length > 1) {
				for (int i = 0; i < dirArray.length - 1; i++) {
					if (dirArray[i] != null && dirArray[i] != null)
						if (!ftpClient.changeWorkingDirectory(dirArray[i])) {
							ftpClient.makeDirectory(dirArray[i]);
							ftpClient.changeWorkingDirectory(dirArray[i]);
						}
				}
			}
			ftpClient.deleteFile(dirArray[dirArray.length - 1]);
			ftpClient.logout();
		} catch (FTPConnectionClosedException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return false;
				}
			}
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return false;
				}
			}
			e.printStackTrace();
			return false;
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * 删除FTP服务器上的文件夹及其下的所有文件和子文件夹--------------bright
	 * 
	 * @param server
	 * @param username
	 * @param password
	 * @param remote
	 * @return
	 */
	public boolean RemoveDirectory(String server, String username,
			String password, String remoteDirectory) throws Exception {
		 
		int reply;
		try {
			ftpClient.connect(server);
			reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				return false;
			}
		} catch (IOException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return false;
				}
			}
			e.printStackTrace();
		}

		try {
			if (!ftpClient.login(username, password)) {
				ftpClient.logout();
				return false;
			}

			boolean bln = ftpClient.changeWorkingDirectory(remoteDirectory);
			if (!bln)
				return false;
			FTPFile[] files = ftpClient.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isFile()) {
					ftpClient.deleteFile(files[i].getName());
				}
				if (files[i].isDirectory()) {
					RemoveDirectory(server, username, password, remoteDirectory
							+ "/" + files[i].getName());
				}
			}
			ftpClient.changeToParentDirectory();
			boolean blRemove = ftpClient.removeDirectory(remoteDirectory);
			ftpClient.logout();
			return blRemove;
		} catch (FTPConnectionClosedException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return false;
				}
			}
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return false;
				}
			}
			e.printStackTrace();
			return false;
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return false;
				}
			}
		}
		// return true;
	}
   
   
   public List getFilNames(String server, String username, String password,
            String remoteDirectory) throws Exception {
       
      int reply;
      try {
         ftpClient.connect(server);
         reply = ftpClient.getReplyCode();
         if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            return null;
         }
      } catch (IOException e) {
         if (ftpClient.isConnected()) {
            try {
               ftpClient.disconnect();
            } catch (IOException f) {
               f.printStackTrace();
               return null;
            }
         }
         e.printStackTrace();
      }

      try {
         if (!ftpClient.login(username, password)) {
            ftpClient.logout();
            return null;
         }

         boolean bln = ftpClient.changeWorkingDirectory(remoteDirectory);
         if (!bln)
            return null;
         
         FTPListParseEngine engine = ftpClient.initiateListParsing();
         FTPFile[] files = null;
         
         ArrayList list = new ArrayList();
         
         while(engine.hasNext()) {
            files = engine.getFiles();
            
            if(files != null)
            break;
         }
         
         if(files == null) {
            return null;
         }
         
         for(FTPFile file : files) {
            list.add(file.getName());
         }
          
         // ftpClient.changeToParentDirectory();
         ftpClient.logout();
         return list;
      } catch (FTPConnectionClosedException e) {
         if (ftpClient.isConnected()) {
            try {
               ftpClient.disconnect();
            } catch (IOException f) {
               f.printStackTrace();
               return null;
            }
         }
         e.printStackTrace();
         return null;
      } catch (IOException e) {
         if (ftpClient.isConnected()) {
            try {
               ftpClient.disconnect();
            } catch (IOException f) {
               f.printStackTrace();
               return null;
            }
         }
         e.printStackTrace();
         return null;
      } finally {
         if (ftpClient.isConnected()) {
            try {
               ftpClient.disconnect();
            } catch (IOException f) {
               f.printStackTrace();
               return null;
            }
         }
      }
   }

	/**
	 * 获取FTP服务器上的文件夹及其下的所有文件和子文件夹--------------bright
	 * 
	 * @param server
	 * @param username
	 * @param password
	 * @param remote
	 * @return
	 */
	public List getFils(String server, String username, String password,
			String remoteDirectory) throws Exception {
		 
		int reply;
		try {
			ftpClient.connect(server);
			reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				return null;
			}
		} catch (IOException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return null;
				}
			}
			e.printStackTrace();
		}

		try {
			if (!ftpClient.login(username, password)) {
				ftpClient.logout();
				return null;
			}

			boolean bln = ftpClient.changeWorkingDirectory(remoteDirectory);
			if (!bln)
				return null;
			FTPFile[] files = ftpClient.listFiles();
			List<FileInfo> fileinfos = new ArrayList<FileInfo>();
			for (int i = 0; i < files.length; i++) {
				FileInfo fileinfo = new FileInfo();
				fileinfo.setFilename(files[i].getName());
				if (files[i].isFile()) {
					fileinfo.setFiletype(true);
				}
				if (files[i].isDirectory()) {
					fileinfo.setFiletype(false);
				}
				fileinfos.add(fileinfo);
			}
			// ftpClient.changeToParentDirectory();
			ftpClient.logout();
			return fileinfos;
		} catch (FTPConnectionClosedException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return null;
				}
			}
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return null;
				}
			}
			e.printStackTrace();
			return null;
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return null;
				}
			}
		}
	}
	
	/**
	 *   demo image
	 * 
	 * @return
	 * @throws Exception
	 */
	public Map<String, Long> getFileInfoFromDir(String server, String username,
			String password, String remoteDirectory) throws Exception {
		
		int reply;
		try {
			ftpClient.connect(server);
			reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				return null;
			}
		} catch (IOException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return null;
				}
			}
			e.printStackTrace();
		}
		try {
			if (!ftpClient.login(username, password)) {
				ftpClient.logout();
				return null;
			}

			boolean bln = ftpClient.changeWorkingDirectory(remoteDirectory);
			if (!bln)
				return null;
			FTPFile[] ftpFileArray = ftpClient.listFiles();

			Map<String, Long> fileInfoMap = new HashMap<String, Long>();
			for (int i = 0; i < ftpFileArray.length; i++) {
				FTPFile ftpFile = ftpFileArray[i];
				if (ftpFile.isFile()) {
					fileInfoMap.put(ftpFile.getName(), ftpFile.getSize());
				}
			}
			return fileInfoMap;
		} catch (FTPConnectionClosedException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return null;
				}
			}
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return null;
				}
			}
			e.printStackTrace();
			return null;
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					f.printStackTrace();
					return null;
				}
			}
		}
	}

	
	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
	/*	PropertyConfig pr = PropertyConfig.getInstance();
		String ftp_server = pr.getProperty("ftp_server");
		String ftp_port = pr.getProperty("ftp_port");
		String ftp_user = pr.getProperty("ftp_user");
		String ftp_password = pr.getProperty("ftp_password");

		UploadFile uploadFile = new UploadFile();
		List files = uploadFile.getFils(ftp_server, ftp_user, ftp_password,
				"/usr/local/apache/htdocs/");
		if (null != files) {
			Iterator fi = files.iterator();
			while (fi.hasNext()) {
				FileInfo fileInfo = (FileInfo) fi.next();
			//	System.out.println(fileInfo.getFilename());
				// System.out.println(fileInfo.isFiletype());
			}
		}*/
		// getFileList(); 
		// System.out.println(TestUpload.uploadFile("D:\\5.doc"));
	}
	
	
}
